package com.itheima.ydd.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.commom.R;
import com.itheima.ydd.dto.SysUserDto;
import com.itheima.ydd.dto.SysUserRoleDto;
import com.itheima.ydd.entity.SysRole;
import com.itheima.ydd.entity.SysUser;
import com.itheima.ydd.service.SysRoleService;
import com.itheima.ydd.service.SysUserService;
import com.itheima.ydd.utils.PageUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 系统用户管理
 */
@Slf4j
@RestController
@RequestMapping("/sys_user")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    /**
     * 系统管理员分页
     *
     * @param login_name
     * @param status
     * @param phone
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/list")
    public R list(String login_name, String status, String phone, int page, int limit) {
        log.info("login_name = {},status = {},page = {},limit = {}", login_name, status, page, limit);

        Integer statusI = "".equals(status) ? -1 : Integer.parseInt(status);

        //分页构造器
        Page<SysUser> sysUserPage = new Page<>(page, limit);
        Page<SysUserDto> sysUserDtoPage = new Page<>();

        //条件构造器
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(login_name), SysUser::getLoginName, login_name);
        queryWrapper.eq(StringUtils.isNotEmpty(String.valueOf(statusI)) && statusI != -1, SysUser::getStatus, statusI);
        queryWrapper.like(StringUtils.isNotEmpty(phone), SysUser::getPhone, phone);

        //执行查询
        sysUserService.page(sysUserPage, queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(sysUserPage, sysUserDtoPage, "records");

        List<SysUser> records = sysUserPage.getRecords();
        List<SysUserDto> list = records.stream().map((item) -> {
            SysUserDto sysUserDto = new SysUserDto();

            BeanUtils.copyProperties(item, sysUserDto);//拷贝普通属性到sysUserDto
            String roleId = item.getRoleId();

            List<String> roleIds = JSON.parseObject(roleId, List.class);
            //根据角色id查询角色对象
            List<SysRole> sysRoles = sysRoleService.listByIds(roleIds);
            List<String> roleName = new ArrayList<>();
            if (sysRoles != null) {
                for (SysRole sysRole : sysRoles) {
                    String name = sysRole.getName();
                    roleName.add(name);
                }
                sysUserDto.setRolename(roleName);
            }
            return sysUserDto;
        }).collect(Collectors.toList());

        sysUserDtoPage.setRecords(list);

        /*List<SysUserDto> records1 = sysUserDtoPage.getRecords();
        Map<String , Object> map = new HashMap<>();
        map.put("data",records1);
        map.put("count",(int)sysUserPage.getTotal());
        map.put("totalPages",(int)sysUserPage.getPages());
        map.put("currentPage",(int)sysUserPage.getCurrent());
        map.put("pageSize",(int)sysUserPage.getSize());*/

        PageUtils<SysUserDto> sysUserDtoPageBean = new PageUtils<>(sysUserDtoPage, sysUserDtoPage.getRecords());
        return R.success("", sysUserDtoPageBean);
    }


    /**
     * 添加系统管理员
     *
     * @param sysUser
     * @return
     */
    @PostMapping("/add")
    //@CacheEvict(value = "SysUserCache", key = "'SysUser_'+#sysUser.id")  //清缓存
    public R add(@RequestBody SysUser sysUser) {
        log.info("系统管理员信息: {}", sysUser.toString());

        //进行md5加密处理
        String password = sysUser.getPassword();
        sysUser.setPassword(DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8)));

        String[] roleIds = sysUser.getRoleIds();
        String s = JSON.toJSONString(roleIds);
        sysUser.setRoleId(s);
        sysUserService.save(sysUser);

        return R.success("", null);
    }

    /**
     * 系统管理员数据回显(根据id)
     *
     * @param id
     * @return
     */
    @GetMapping("/rowInfo")
    public R rowInfo(String id) {
        log.info("id为: {}", id);

        SysUser sysUser = sysUserService.getById(id);
        String password = "";
        sysUser.setPassword(password);
        if (sysUser != null) {
            SysUserRoleDto sysUserRoleDto = new SysUserRoleDto();
            BeanUtils.copyProperties(sysUser, sysUserRoleDto, "roleId");
            String roleId = sysUser.getRoleId();
            roleId = roleId.substring(1, roleId.length() - 1);
            String[] split = roleId.split(",");
            ArrayList<String> roleIds = new ArrayList<>();
            for (String s : split) {
                s = s.substring(1, s.length() - 1);
                roleIds.add(s);
            }
            sysUserRoleDto.setRoleId(roleIds);

            return R.success("", sysUserRoleDto);
        }

        return R.error("没有查询到对应的系统管理员信息");
    }


    /**
     * 修改系统管理员信息
     *
     * @param sysUser
     * @return
     */
    @PostMapping("/update")
    //@CacheEvict(value = "SysUserCache", key = "'SysUser_'+#sysUser.id")  //清缓存
    public R update(@RequestBody SysUser sysUser) {
        log.info(sysUser.toString());
        String password = sysUser.getPassword();
        //如果密码不为空,将重新加密保存到数据库
        if(!Objects.equals(password, "")){
            String[] roleIds = sysUser.getRoleIds();
            String s = JSON.toJSONString(roleIds);
            sysUser.setRoleId(s);
            //进行md5加密处理
            sysUser.setPassword(DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8)));
            sysUserService.updateById(sysUser);
        }

        //如果密码为空,将使用原来密码
        SysUser byId = sysUserService.getById(sysUser.getId());
        sysUser.setPassword(byId.getPassword());
        sysUserService.updateById(sysUser);

        return R.success("", null);
    }

    /**
     * 删除系统管理员
     *
     * @param id
     * @return
     */
    @GetMapping("/del")
    //@CacheEvict(value = "SysUserCache",allEntries = true) //清除SysUserCache名称下,所有的缓存数据
    public R delete(String id) {
        log.info("id为: {}", id);

        sysUserService.removeById(id);

        return R.success("", null);
    }
}
